<template>
  <div class="home-container">
    <el-container>
      <el-header>
        <div class="header-content">
          <h1>十三水</h1>
          <div class="user-info">
            <el-dropdown @command="handleCommand">
              <span class="user-dropdown">
                {{ userInfo?.nickname }}
                <el-icon><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>
      
      <el-main>
        <div class="room-list">
          <div class="header">
            <h2>房间列表</h2>
            <el-button type="primary" @click="handleCreateRoom">创建房间</el-button>
          </div>

          <!-- 桌面端表格视图 -->
          <div class="desktop-view">
            <el-table :data="rooms" style="width: 100%">
              <el-table-column prop="roomCode" label="房间号" width="120" />
              <el-table-column label="当前人数" width="100">
                <template #default="{ row }">
                  {{ row.playerCount || 0 }}/4
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getStatusType(row.status)">
                    {{ getStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="handleJoinRoom(row)"
                    :disabled="row.status !== 'WAITING' || row.playerCount >= 4"
                  >
                    加入
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="handleDeleteRoom(row)"
                    v-if="userInfo?.id && isCreator(row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 移动端卡片视图 -->
          <div class="mobile-view">
            <el-card v-for="room in rooms" :key="room.roomCode" class="room-card">
              <div class="room-info">
                <div class="room-header">
                  <span class="room-code">房间号: {{ room.roomCode }}</span>
                  <el-tag :type="getStatusType(room.status)" size="small">
                    {{ getStatusText(room.status) }}
                  </el-tag>
                </div>
                <div class="room-details">
                  <div class="detail-item">
                    <span class="label">人数:</span>
                    <span>{{ room.playerCount || 0 }}/4</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">创建时间:</span>
                    <span>{{ formatDate(room.createTime) }}</span>
                  </div>
                </div>
                <div class="room-actions">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="handleJoinRoom(room)"
                    :disabled="room.status !== 'WAITING' || room.playerCount >= 4"
                  >
                    加入
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="handleDeleteRoom(room)"
                    v-if="userInfo?.id && isCreator(room)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>
          
          <!-- 无房间时显示 -->
          <el-empty 
            v-if="rooms.length === 0" 
            description="暂无可用房间" 
            class="empty-rooms"
          >
            <el-button type="primary" @click="handleCreateRoom">创建房间</el-button>
          </el-empty>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import { roomApi } from '@/api/room'
import type { UserInfo } from '@/types/user'
import type { Room, Result } from '@/types/room'

const router = useRouter()
const userInfo = ref<UserInfo>()
const rooms = ref<Room[]>([])

// 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await userApi.getUserInfo()
    if (res.code === 200 && res.data) {
      userInfo.value = res.data
    } else {
      ElMessage.error(res.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 退出登录
const handleCommand = async (command: string) => {
  if (command === 'logout') {
    try {
      const res = await userApi.logout()
      if (res.code === 200) {
        localStorage.removeItem('token')
        ElMessage.success('退出登录成功')
        router.push('/login')
      } else {
        ElMessage.error(res.message || '退出登录失败')
      }
    } catch (error) {
      console.error('退出登录失败:', error)
      ElMessage.error('退出登录失败')
    }
  }
}

// 加载房间列表
const loadRooms = async () => {
  try {
    const res = await roomApi.getAvailableRooms()
    if (res.code === 200) {
      rooms.value = res.data
      console.log('房间数据:', rooms.value) // 添加日志便于调试
    } else {
      ElMessage.error(res.message || '加载房间列表失败')
    }
  } catch (error) {
    console.error('加载房间列表失败:', error)
    ElMessage.error('加载房间列表失败')
  }
}

// 创建房间
const handleCreateRoom = async () => {
  try {
    const res = await roomApi.createRoom()
    if (res.code === 200 && res.data) {
      ElMessage.success('创建房间成功')
      router.push(`/game/${res.data.roomCode}`)
    } else {
      ElMessage.error(res.message || '创建房间失败')
    }
  } catch (error) {
    console.error('创建房间失败:', error)
    ElMessage.error('创建房间失败')
  }
}

// 加入房间
const handleJoinRoom = async (room: Room) => {
  try {
    const res = await roomApi.joinRoom(room.roomCode)
    if (res.code === 200) {
      ElMessage.success('加入房间成功')
      router.push(`/game/${room.roomCode}`)
    } else {
      ElMessage.error(res.message || '加入房间失败')
    }
  } catch (error) {
    console.error('加入房间失败:', error)
    ElMessage.error('加入房间失败')
  }
}

// 删除房间
const handleDeleteRoom = async (room: Room) => {
  try {
    await ElMessageBox.confirm('确定要删除该房间吗？', '提示', {
      type: 'warning'
    })
    const res = await roomApi.deleteRoom(room.roomCode)
    if (res.code === 200) {
      ElMessage.success('删除房间成功')
      await loadRooms()
    } else {
      ElMessage.error(res.message || '删除房间失败')
    }
  } catch (error) {
    console.error('删除房间失败:', error)
    ElMessage.error('删除房间失败')
  }
}

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'WAITING':
      return 'success'
    case 'PLAYING':
      return 'warning'
    case 'FINISHED':
      return 'info'
    default:
      return ''
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'WAITING':
      return '等待中'
    case 'PLAYING':
      return '游戏中'
    case 'FINISHED':
      return '已结束'
    default:
      return status
  }
}

// 格式化日期
const formatDate = (dateStr: string | Date | undefined) => {
  if (!dateStr) return '未知时间';
  
  try {
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) return '无效日期';
    
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch (e) {
    console.error('日期格式化错误:', e);
    return '日期错误';
  }
}

// 判断是否为房间创建者
const isCreator = (room: Room) => {
  return room.creatorId === userInfo.value?.id;
}

onMounted(() => {
  getUserInfo()
  loadRooms()
})
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  background-color: #f0f2f5;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.user-dropdown {
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
}

.room-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

/* 响应式布局 */
.mobile-view {
  display: none;
}

.room-card {
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.room-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.room-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.room-code {
  font-weight: bold;
  font-size: 16px;
}

.room-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-item {
  display: flex;
  gap: 8px;
}

.label {
  color: #909399;
}

.room-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 8px;
}

.empty-rooms {
  margin-top: 40px;
}

/* 媒体查询 - 移动端 */
@media screen and (max-width: 768px) {
  .desktop-view {
    display: none;
  }
  
  .mobile-view {
    display: block;
  }
  
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .header h2 {
    margin-bottom: 8px;
  }
  
  .el-header {
    padding: 0 15px;
  }
  
  .el-main {
    padding: 10px;
  }
  
  .room-list {
    padding: 10px;
  }
}

/* 平板布局 */
@media screen and (min-width: 769px) and (max-width: 1024px) {
  .desktop-view {
    display: block;
  }
  
  .mobile-view {
    display: none;
  }
  
  .el-table {
    font-size: 14px;
  }
}
</style> 